package pro.cherish.quartzlockdemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

@Configuration
public class QuartzConfig {

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        //填写刚刚创建的配置文件名
        propertiesFactoryBean.setLocation(new ClassPathResource("quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /**
     * 3.任务调度 ,创建scheduler
     *
     * @throws IOException
     */


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(@Autowired SpringJobFactory springJobFactory) throws IOException {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobFactory(springJobFactory);
        return schedulerFactoryBean;
    }


   /* @Bean
    public SchedulerFactoryBean schedulerFactoryBean(@Autowired Trigger myTrigger,
                                                     @Autowired SpringJobFactory springJobFactory) throws IOException {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setJobDetails(myJobDetail());
        schedulerFactoryBean.setTriggers(myTrigger);
        //###增加此代码即可
        schedulerFactoryBean.setQuartzProperties(quartzProperties());
        //注意这里需要将我们重写的jobFactory加入才能生效
        schedulerFactoryBean.setJobFactory(springJobFactory);
        return schedulerFactoryBean;
    }


    @Bean
    public JobDetail myJobDetail() {
        JobDetail jobDetail = JobBuilder.newJob(HiJob.class)
                .withIdentity("myJob1", "myJobGroup1")
                //JobDataMap可以给任务execute传递参数
                .usingJobData("job_param", "job_param1")
                .storeDurably()
                .build();
        return jobDetail;
    }

    @Bean
    public Trigger myTrigger() {
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(myJobDetail())
                .withIdentity("myTrigger1", "myTriggerGroup1")
                .usingJobData("job_trigger_param", "job_trigger_param1")
                .startNow()
                //.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(5).repeatForever())
                .withSchedule(CronScheduleBuilder.cronSchedule("* 0/5 * * * ? 2020"))
                .build();
        return trigger;
    }*/

}